﻿/************************************************************************
* Copyright (c) 2018 All Rights Reserved.
*命名空间：Wx.Sdk.Api.Base
*文件名： Api
*创建人： kingling
*创建时间：2018/10/7 10:17:35
*描述
*=======================================================================
*修改标记
*修改时间：2018/10/7 10:17:35
*修改人：kingling
*描述：
************************************************************************/

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Wx.Sdk.Api;
using Wx.Sdk.Api.Base;
using Wx.Sdk.Api.Options;
using Wx.Sdk.Api.Src;

namespace Microsoft.Extensions.DependencyInjection
{
    public static class Api
    {
        /// <summary>
        /// 调用API 需要实现Message
        /// </summary>
        /// <typeparam name="TMessage">Message</typeparam>
        /// <param name="services"></param>
        /// <returns></returns>
        public static IServiceCollection AddWeChatApiMessage<TMessage>(this IServiceCollection services) where TMessage : WxMessage
        {
            services.TryAddScoped<IWxMessage, TMessage>();
            return services;
        }
        /// <summary>
        /// 调用API 需要实现IWxCache
        /// </summary>
        /// <typeparam name="TCache">IWxCache</typeparam>
        /// <param name="services"></param>
        /// <returns></returns>
        public static IServiceCollection AddWeChatApiCache<TCache>(this IServiceCollection services) where TCache : class, IWxCache
        {
            services.RemoveAll<IWxCache>();
            services.TryAddSingleton<IWxCache, TCache>();
            return services;
        }
        /// <summary>
        /// 调用API 不使用接收消息与被动回复功能
        /// </summary>
        /// <param name="services"></param>
        /// <param name="configuration"></param>
        /// <returns></returns>
        public static IServiceCollection AddWeChatApi(this IServiceCollection services, IConfiguration configuration)
        {
            services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            services.AddHttpClient();
            services.TryAddSingleton<WxApi>();
            services.TryAddSingleton<IWxCache, DefaultWxCache>();
            services.Configure<ApiOption>(configuration);
            return services;
        }
        /// <summary>
        /// 注册微信消息中间件
        /// </summary>
        /// <param name="app"></param>
        public static void AddWeChatApiMessageMiddleware(this IApplicationBuilder app)
        {
            app.UseMiddleware<ApiMiddleware>();
        }
    }
}

